Ext.define('MyApp.controller.catalog.CatalogController', {
	extend : 'Ext.app.Controller',
	views : ['catalog.CatalogView','catalog.DocInfoView','dataview.MultiSortButton','catalog.UploadFileForm','catalog.FileMassageView'],
	stores : ['CatalogStore','DocInfoStore'],
	models : ['CatalogEntity','DocInfoEntity'],
	requires : [ 'Ext.ux.BoxReorderer',
	            'Ext.ux.DataView.Animated'],
	refs : [{
				ref : 'catalogviewtree',
				selector : 'catalogview treepanel'
			},
			{
				ref : 'docinfoview',
				selector : 'catalogview docinfoview'
			}],
	init : function() {
		this.control({
					'docinfoview button[type=filterButton]' : {
								click : 'onClickFilterButton'
							},
					'docinfoview button#clearFilterButton' : {
								click : 'onClickClearFilterButton'
					},
					'filemassageview button#dw0xf019':{
						click:function(btn){
							var record = btn.up('form').getForm().getRecord();
							window.open("docinfo/download/"+record.get('id')); 
						}
					},
					'docinfoview dataview' : {
							itemdblclick : function(view ,rec,node ,index,e){
									this.onFilemassageShow(rec);
							},
							itemcontextmenu: function(view, rec, node, index, e) {
										var me = this;
					                    e.stopEvent();
					                    Ext.create('Ext.menu.Menu', {
									        items: [
											           {glyph:0xf019,text: '下载文档', itemid:'download',
											   					 handler: function(widget, event) {
											   					 	window.open("docinfo/download/"+rec.get('id')); 
															     }
											           },
													   {glyph:0xf00b,text: '查看详情', itemid:'detail',
													   			 handler: function(widget, event) {
													   			 	me.onFilemassageShow(rec);
																	
														}
													   }
									        		]
									    }).showAt(e.getXY());
					                    return false;
					                }
					},
					'catalogview button#add' : {
						click : function(btn) {
							this.addNode('next');
						}
					},
					'catalogview button#upload' : {
						click : function(btn) {
							var me = this;
							var record = me.getCatalogviewtree().getSelectionModel()
										.getLastSelected();
							if(record){
								   Ext.create('Ext.Window', {
								        title: '文件上传',
								        width: 400,
								        height: 300,
								        layout: 'fit',
								        modal: true,//遮盖
								        items: {
								            xtype:'uploadfileform',
								            catalogId:record.get('id')
								        }
								    }).show();
							}else{
								Ext.MessageBox.alert('提示', '请先选择记录!');
							}
						}
					},
					'uploadfileform button#up0xf093':{
						click:function(btn){
							var me=this,formPanle = btn.up('form'), 
								form = formPanle.getForm(),record = me.getCatalogviewtree().getSelectionModel()
										.getLastSelected();
								if (form.isValid()) {
									form.setValues({
												catalogId : formPanle.catalogId
											});
									btn.up('form').getForm().submit({
										url : 'docinfo/upload',
										submitEmptyText : false,
										waitMsg : '请稍等，文件正在上传!',
										success : function(fp, o) {
											var text = Ext.decode(o.response.responseText);
											if (text.success != '0') {
												Ext.MessageBoxUtil.msg('提示', '上传成功!');
												formPanle.up('window').close();
													me.getDocinfoview().down('dataview').getStore().removeAll();
													me.getDocinfoview().down('dataview').getStore().load({
													    scope: this,
													    params:{
													    	catalogId:record.get('id')
					    								},
													    callback: function(records, operation, success) {
													    }
													});
											} else {
												Ext.MessageBoxUtil.msg('提示', '上传失败!');
											}
										},
										failure : function(form, action) {
											Ext.MessageBoxUtil.msg('提示',
													'上传失败,服务器发生错误!');
										}
									});
								}
						}
					},
					'catalogview button#delete' : {
						click : function(btn) {
								var me = this;
								var record = me.getCatalogviewtree().getSelectionModel()
										.getLastSelected();
								if(record){
									if (!record.isLeaf()) {
										Ext.MessageBox.alert('提示', '此记录包括子记录,需先删除子记录!');
									} else {
										Ext.MessageBox.confirm('提示', '确定要删除此记录吗?', function showResult(
												btnResult) {
											if (btnResult == 'yes') {
												var parentNode = record.parentNode;
												if (parentNode.childNodes.length == 1) {
													parentNode.set('leaf', true);
												}
												record.remove();
												me.getCatalogviewtree().getStore().sync({
													success : function(response) {
														var text = Ext
																.decode(response.operations[0].response.responseText);
														if (text == 1) {
															Ext.MessageBoxUtil.msg('提示', '操作成功!');
														} else {
															Ext.MessageBoxUtil.msg('提示', '操作失败!');
														}
													},
													failure : function(response, options) {
														Ext.MessageBoxUtil.msg('提示', '操作失败,错误编号：'
																		+ response.status);
													}
												});
											}
										});
									}
								}else{
									Ext.MessageBox.alert('提示', '请先选择记录!');
								}
						}
					},
					'catalogview treepanel > treeview' : {
							drop : function(node, data, overModel, dropPosition) {
								if(!overModel.isLeaf()){
									var record = data.records[0];
									Ext.Ajax.request({
									    url: 'catalog/updateCatalogParent',
									    params: {
									        id: record.get('id'),
									        newParent:overModel.get('id')
									    },
									    success: function(response){
									        var text = response.responseText;
									        if(text==1){
									        	Ext.MessageBoxUtil.msg('提示','提交成功!');
									        }else{
									        	Ext.MessageBoxUtil.msg('提示','提交失败!');
									        }
									    }
									});
								}
							},
							beforedrop:function(node, data, overModel, dropPosition, dropHandlers) {
							    dropHandlers.wait = true;
							    if(overModel.isLeaf()){
							    	 dropHandlers.cancelDrop();
							    }else{
							    	 dropHandlers.processDrop();
							    }
							}	
					},
					'catalogview tool[type=refresh]':{
						click:function(){
							this.getCatalogviewtree().getStore().reload({
								scope : this,
								callback : function(records, operation, success) {
								}
							});
						}
					},
					'catalogview tool[type=expand]':{
						click:function(){
							 this.getCatalogviewtree().expandAll();
						}
					},
					'catalogview tool[type=collapse]':{
						click:function(){
							 this.getCatalogviewtree().collapseAll();
						}
					},
					'catalogview treepanel':{
						selectionchange : function(selModel, records) {
							var me = this;
							if (records[0]) {
								me.getDocinfoview().down('dataview').getStore().removeAll();
								me.getDocinfoview().down('dataview').getStore().load({
								    scope: this,
								    params:{
								    	catalogId:records[0].get('id')
    								},
								    callback: function(records, operation, success) {
								    }
								});
							}
						},
						edit:function(editor,e){
							var record = editor.context.record;
							this.getCatalogStoreStore().sync({
								success : function(response) {
										var text = Ext.decode(response.operations[0].response.responseText);
										if (text == '0') {
											Ext.MessageBoxUtil.msg('提示', '数据提交失败!');
										} else {
											if(record.get('id')==null){
												record.set('id',text.id);
											}
											Ext.MessageBoxUtil.msg('提示', '数据提交成功!');
										}
									}
							});
						}
					}
				});
	},
	onFilemassageShow:function(re){
		var win = Ext.widget('filemassageview', {animateTarget : document.body});
		win.down('form').getForm().loadRecord(re);
		win.show();
	},
	onClickFilterButton : function(widget) {
				dataIndex = widget.dataIndex;
				dataFilter = widget.dataFilter;
				view = widget.up('docinfoview').down('dataview');
				var store = view.getStore();
				store.suspendEvents();
				store.clearFilter();
				store.resumeEvents();
				store.filter([{
							fn : function(record) {
								return record.get(dataIndex) == dataFilter;
							}
						}]);
				store.filter([{
							fn : function(record) {
								return record.get(dataIndex) == dataFilter;
							}
					}]);
			},
	onClickClearFilterButton : function(widget) {
				view = widget.up('docinfoview').down('dataview');
				var store = view.getStore();
				store.clearFilter();
				store.filter([{
							fn : function(record) {
								return record;
							}
						}]);
			},
	addNode : function(param) {
		var me = this;
		var treepanel = me.getCatalogviewtree(),
			selModel = treepanel.getSelectionModel(), 
			lastselect = selModel.getLastSelected();
			cellEditingPlugin = treepanel.plugins[0],  
			parentNode = null;
			
		if(lastselect){
			if ('next' == param) {
				parentNode = selModel.getLastSelected();
			} else {
				var selectNode = selModel.getLastSelected();
				parentNode = selectNode.parentNode;
			}
		}else{
			parentNode = treepanel.getRootNode( );
		}
		newNode = Ext.create('MyApp.model.CatalogEntity', {
				text : '新建目录',
				leaf : true,
				parentId : parentNode.get('id'),
				userId:Ext.user.get('id'),
				loaded : true
			});
		if (parentNode.isLeaf()) {
			parentNode.set('leaf', false);
		}
		if (!parentNode.isExpanded()) {
			treepanel.on('afteritemexpand', function startEdit(list) {  
                    if(list === parentNode) {  
                    	parentNode.appendChild(newNode);
                   		selModel.select(newNode);  
           				cellEditingPlugin.startEdit(newNode, 0);
                        treepanel.un('afteritemexpand', startEdit);  
                    }  
            	}); 
			parentNode.expand(false,function(op){
			});
		}else{
			parentNode.appendChild(newNode);
			selModel.select(newNode);  
            cellEditingPlugin.startEdit(newNode, 0); 
		}
	}
});